package ie.lawlor.amvc.swing;

import ie.lawlor.amvc.IDialogEnabledView;
import ie.lawlor.amvc.IView;
import ie.lawlor.amvc.event.Event;

import java.awt.Component;

import javax.swing.JDialog;
import javax.swing.JFrame;


/**
 * @author blawlor
 *
 */
public class SwingDialogEnabledViewProxy extends SwingViewProxy implements IDialogEnabledView {

	private SwingDialogEnabledView view;
	private boolean usingDialog = false;
	protected JDialog dialog = new JDialog();    
	
	/**
	 * @param view
	 */
	public SwingDialogEnabledViewProxy(String name, SwingDialogEnabledView view) {
		super(name, view);
		this.view = view;
	}

	public SwingDialogEnabledViewProxy(SwingDialogEnabledView view) {
		super(view);
		this.view = view;
	}

    /**
     * @param usingDialog
     */
    public void setUsingDialog(boolean usingDialog) {
        this.usingDialog = usingDialog;
    }

	/* (non-Javadoc)
	 * @see com.informatica.amvc.DialogEnabledView#setModel(boolean)
	 */
	public void setModal(boolean modal) {
		dialog.setModal(modal);
	}

	/* (non-Javadoc)
	 * @see com.informatica.amvc.DialogEnabledView#setTitle(java.lang.String)
	 */
	public void setTitle(String title) {
		dialog.setTitle(title);
	}

	/* (non-Javadoc)
	 * @see com.informatica.amvc.swing.SwingDialogEnabledView#getDialog()
	 */
	public JDialog getDialog() {
		return dialog;
	}

    /**
     * @return
     */
    public boolean isUsingDialog() {
        return usingDialog;
    }

	
	/* (non-Javadoc)
	 * @see com.informatica.amvc.DialogEnabledView#setParent(com.informatica.amvc.View)
	 */
	public void setParent(IView parentView, String parentViewName) {
		logger.debug("Entering");
		super.setParent(parentView, parentViewName);
		if (usingDialog){
			if (parentView instanceof JFrame) {
				dialog = new JDialog((JFrame)parentView, dialog.getTitle(), dialog.isModal());
			}else {
				IView nextView = parentView.getParentView();
				while (!(nextView instanceof JFrame)){
					nextView = nextView.getParentView();
				}
				if (nextView != null){
					dialog = new JDialog((JFrame)nextView, dialog.getTitle(), dialog.isModal());
				}
			}
		}
	}
	
    //TODO A more efficent solution would be to block the event entirely.
	public void doHideView(Event e){
		logger.debug("Entering");
//		if (isVisible()){
			if (isUsingDialog()){
				getDialog().hide();
			} 
//      else {
//				((Container)parentView).removeAll();
//			}
//		} 
	}
	
	public void doShowView(Event e){
		logger.debug("Entering");
		if (!isVisible()){
			if (isUsingDialog()) {
				getDialog().getContentPane().add((Component)view);
				getDialog().pack();
				getDialog().setLocationRelativeTo(getDialog().getParent());
				getDialog().show();
			} else {
				super.doShowView(e);
			}
		}
	}	
}
